import { isArray, result } from 'lodash';
import { fetch_all_phase, fetch_cases_by_phase_ids, update_tag_by_case_id } from '../api/api.js';


import _ from 'lodash'

const state = {
  phase_list: [],
  case_list: [],
}

const getters = {
  phase_list: (state, getters, rootState) => {
    return state.phase_list;
  },
  case_list: (state, getters, rootState) => {
    return state.case_list;
  },

  case_count: (state, getters, rootState) => {
    return state.case_list.length;
  }
}

// actions处理异步
const actions = {

  // 获取所有列表
  fetch_all_phase({
    commit
  }) {

    fetch_all_phase().then(res => {
      commit('setPhase', res);
      if (isArray(res)) {
        var rs = _.reduce(res, (rra, item) => {
          rra.push(item._id["$oid"])
          return rra
        }, [])

        fetch_cases_by_phase_ids(rs).then(res => {
          commit('setCases', res);
        });
      }

    });
  },

  // 根据列表id获取案件列表
  fetch_cases_by_phase_ids({
    commit
  }, {
    payload
  }) {

    fetch_cases_by_phase_ids(payload).then(res => {
      commit('setCases', res);
    });
  },

  // 根据caseId更新标签列表
  update_tag_by_case_id({
    commit
  }, {
    payload
  }) {
    update_tag_by_case_id(payload.caseId, payload.tags).then(res => {
      // commit('setTags', res)
    })
  },

}

// mutation 必须同步，任何异步只能出现在 action 里
const mutations = {
  // 列表
  setPhase(state, payload) {
    state.phase_list = payload;
  },
  // 案件
  setCases(state, payload) {
    state.case_list = payload
  },

}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
